package com.icoolkj.microservices.order.service;

import com.icoolkj.microservices.order.client.InventoryClient;
import com.icoolkj.microservices.order.dto.InventoryResponse;
import com.icoolkj.microservices.order.dto.OrderLineItemsDto;
import com.icoolkj.microservices.order.dto.OrderRequest;
import com.icoolkj.microservices.order.model.Order;
import com.icoolkj.microservices.order.model.OrderLineItems;
import com.icoolkj.microservices.order.repository.OrderRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author icoolkj
 * @version 1.0
 * @description
 * @createDate 2024/11/10 21:22
 */
@Service
@RequiredArgsConstructor
@Transactional
@Slf4j
public class OrderService {

    private final OrderRepository orderRepository;
    private final InventoryClient inventoryClient;

    public void placeOrder(OrderRequest orderRequest){
        Order order = new Order();
        order.setOrderNumber(UUID.randomUUID().toString());

        List<OrderLineItems> orderLineItems = orderRequest.getOrderLineItemsDtoList()
                .stream()
                .map(this::mapToDto)
                .toList();

        order.setOrderLineItemsList(orderLineItems);

        List<String> skuCodes = order.getOrderLineItemsList().stream()
                        .map(OrderLineItems::getSkuCode).toList();
        List<InventoryResponse> inventoryResponseArray = inventoryClient.isInStock(skuCodes);

        boolean allProductsInStock = inventoryResponseArray.stream()
                        .allMatch(InventoryResponse::isInStock);

        if(allProductsInStock){
            orderRepository.save(order);
            log.info("Order Plasced Successfully !");
        } else {
            throw new IllegalArgumentException("Product is not in stock, please try again later.");
        }


    }

    private OrderLineItems mapToDto(OrderLineItemsDto orderLineItemsDto) {
        OrderLineItems orderLineItems = new OrderLineItems();
        orderLineItems.setPrice(orderLineItemsDto.getPrice());
        orderLineItems.setSkuCode(orderLineItemsDto.getSkuCode());
        orderLineItems.setQuantity(orderLineItemsDto.getQuantity());
        return orderLineItems;
    }
}